<template>
  <div class="apply">
    <navBar title="订单提交" @onClickLeft="onClickLeft" />
    <div class="apply-form">
      <van-form validate-first>
        <van-field
          class="van-field-isRequired"
          readonly
          clickable
          name="agency"
          :value="form.agency"
          label="报销地点"
          placeholder="点击选择报销地点"
          :rules="[{ required: true, message: '请选择报销地点' }]"
          @click="showSelectServiceAgency = true"
        />
        <van-field
          class="van-field-isRequired"
          readonly
          clickable
          name="item"
          :value="form.item"
          label="代办事项"
          placeholder="点击选择代办事项"
          :rules="[{ required: true, message: '请选择代办事项' }]"
          @click="showSelectServiceItem = true"
        />
        <van-field
          class="van-field-isRequired"
          readonly
          clickable
          name="type"
          :value="form.type"
          label="服务类型"
          placeholder="点击选择服务类型"
          :rules="[{ required: true, message: '请选择服务类型' }]"
          @click="showSelectServiceType = true"
        />
        <van-field
          class="van-field-isRequired"
          readonly
          clickable
          name="time"
          :value="form.time"
          label="服务时间"
          placeholder="点击选择服务时间"
          :rules="[{ required: true, message: '请选择服务时间' }]"
          @click="showSelectServiceTime = true"
        />
        <van-field
          name="file"
          label="服务文件"
          :rules="[{ required: true, message: '请选择服务文件' }]"
          class="van-field-isRequired needTips"
        >
          <!-- accept=".zip, .rar, aplication/zip" -->
          <template #input>
            <van-uploader
              upload-icon="todo-list-o"
              v-model="fileList"
              :before-read="beforeRead"
              :after-read="afterRead"
              :multiple="true"
              :max-count="5"
            />
            <p class="tips">专利报销资料需要：受理通知书，缴费通知书，公务卡刷卡记录(公务卡报销必须有)</p>
          </template>
        </van-field>
        <van-field
          name="file"
          label="发票文件"
          :rules="[{ required: true, message: '请选择发票文件' }]"
          class="van-field-isRequired needTips"
        >
          <!-- accept=".zip, .rar, aplication/zip" -->
          <template #input>
            <van-uploader
              upload-icon="todo-list-o"
              v-model="invFirstList"
              :before-read="invBeforeRead"
              :after-read="invAfterRead"
              :max-count="1"
            />
            <p class="tips">发票文件只能上传一个，如有多个文件请分开提交订单</p>
          </template>
        </van-field>
        <van-field name="official_card" label="公务卡支付" class="needTips">
          <template #input>
            <van-switch v-model="form.officialCard" size="20" @change="officialCardChange" />
            <p class="tips">如果专利缴费时使用公务卡才能选择公务卡支付，否则无需选择。</p>
          </template>
        </van-field>
      </van-form>

      <van-submit-bar
        text-align="left"
        button-color="#0016FF"
        :price="reallyPrice"
        :suffix-label="originalPrice"
        button-text="提交订单"
        @submit="onSubmit"
      />
      <van-popup v-model="showSelectServiceItem" position="bottom">
        <van-picker
          show-toolbar
          :columns="selectServiceItemColumns"
          @confirm="selectServiceItemConfirm"
          @cancel="showSelectServiceItem = false"
          default-index="0"
        />
      </van-popup>
      <van-popup v-model="showSelectServiceType" position="bottom">
        <van-picker
          show-toolbar
          :columns="selectServiceTypeColumns"
          @confirm="selectServiceTypeConfirm"
          @cancel="showSelectServiceType = false"
          default-index="0"
        />
      </van-popup>
      <van-popup v-model="showSelectServiceTime" position="bottom">
        <van-picker
          show-toolbar
          :columns="selectServiceTimeColumns"
          @confirm="selectServiceTimeConfirm"
          @cancel="showSelectServiceTime = false"
          default-index="1"
        />
      </van-popup>
      <van-popup v-model="showSelectServiceAgency" position="bottom">
        <van-picker
          show-toolbar
          :columns="selectServiceAgencyColumns"
          @confirm="selectServiceAgencyConfirm"
          @cancel="showSelectServiceAgency = false"
          default-index="0"
        />
      </van-popup>
    </div>
  </div>
</template>

<script>
import navBar from "@cb/navBar.vue";
import { getOrderPrice, applyOrder, getServiceAgency } from "@a/order.js";
import axios from "axios";
import { Dialog, Toast } from "vant";
export default {
  components: {
    navBar,
  },
  data() {
    return {
      form: {
        item: "",
        type: "",
        time: "",
        agency: "",
        officialCard: false,
      },
      fileList: [],
      invFirstList: [],
      selectServiceItemColumns: [
        {
          text: "签字",
          id: 1,
        },
        // {
        //   text: "报销",
        //   id: 2,
        // },
        {
          text: "签字和报销",
          id: 3,
        },
      ],
      selectServiceTypeColumns: [
        {
          text: "专利",
          id: 1,
        },
        {
          text: "保险",
          id: 2,
        },
        {
          text: "论文",
          id: 3,
        },
        {
          text: "其他",
          id: 4,
        },
      ],
      selectServiceTimeColumns: [
        {
          text: "15天",
          id: 15,
        },
        {
          text: "30天",
          id: 30,
        },
        // {
        //   text: "45天",
        //   id: 45,
        // },
      ],
      selectServiceAgencyColumns: [],
      showSelectServiceType: false,
      showSelectServiceItem: false,
      showSelectServiceTime: false,
      showSelectServiceAgency: false,
      // params: {
      //   service_type: null,
      //   service_project: null,
      //   service_time: null,
      //   service_file: null
      // },
      params: new FormData(),
      price: 0,
      reallyPrice: 0,
      baseUrl: process.env.VUE_APP_ORIGIN_URL,
      fileIndex: 1,
    };
  },
  computed: {
    originalPrice() {
      return `￥${this.price}`;
    },
  },
  watch: {
    form: {
      handler: function (val) {
        if (val.item && val.type && val.time) {
          this.getOrderPrice();
        }
      },
      deep: true,
    },
  },
  created() {
    this.getServiceAgency();
  },
  methods: {
    officialCardChange(value) {
      // this.params.set("is_official_card", value ? 1 : 2);
    },
    setDefult(data) {
      this.form.item = data.default_project;
      this.form.type = data.default_type;
      this.form.time = data.default_time;

      this.params.set(
        "service_type",
        this.selectServiceTypeColumns.find(
          (item) => item.text == data.default_type
        ).id
      );

      this.params.set(
        "service_project",
        this.selectServiceItemColumns.find(
          (item) => item.text == data.default_project
        ).id
      );
      this.params.set(
        "service_time",
        this.selectServiceTimeColumns.find(
          (item) => item.text == data.default_time
        ).id
      );
    },
    beforeRead(file) {
      // if (
      //   !["zip", "rar", "x-zip-compressed"].includes(file.type.split("/")[1])
      // ) {
      //   Dialog.alert({
      //     title: "提示",
      //     message: "请上传zip/rar压缩文件",
      //   });
      //   return false;
      // }
      return true;
    },
    afterRead(file) {
      if (file.length) {
        file.forEach((item, index) => {
          if (index) {
            this.fileIndex++;
          }
          this.params.append(`service_file${this.fileIndex}`, item.file);
        });
        this.fileIndex++;
      } else {
        this.params.append(`service_file${this.fileIndex}`, file.file);
        this.fileIndex++;
      }
    },
    invBeforeRead(file) {
      return true;
    },
    invAfterRead(file) {
      this.params.append(`invoice_file`, file.file);
    },
    submitPost() {
      this.params.set("is_official_card", this.form.officialCard ? 1 : 2);
      applyOrder(this.params).then((res) => {
        if (res.code === 200) {
          let isNoOA = this.$store.state.user.ex_info && this.$store.state.user.ex_info.oa_phone ? false : true
          if (res.data.service_project == 3 && isNoOA) {
            Dialog.alert({
              title: "提交订单成功！",
              message:
                "您还没有绑定OA账号，这会影响到您的订单进度，请尽快完善资料。",
              confirmButtonText: "立即绑定",
              closeOnClickOverlay: true
            })
              .then(() => {
                this.$router.push("/user/set/setOAAccount");
              })
          } else {
            Toast.success(`提交订单成功！`);
          }


          this.$router.push({
            path: "/pay/payMethod",
            query: {
              pay_info_id: res.data.pay_info.id,
              front_url: `${this.baseUrl}/user/home`,
            },
          });
        } else {
          Dialog.alert({
            title: "提示",
            message: res.data,
          });
        }
      });
    },
    onClickLeft() {
      this.$router.go(-1);
    },
    onFailed() {},
    selectServiceItemConfirm(value) {
      // if ((value.id == 1 || value.id == 2) && this.form.time == "45天") {
      //   Dialog.alert({
      //     title: "提示",
      //     message: "只有“签字和报销”才能选择45天服务时间，请重新选择",
      //   });
      //   return;
      // }

      // if(value.id == 3 && this.form.time == '15天') {
      //   Dialog.alert({
      //     title: "提示",
      //     message: "“签字和报销”流程相对麻烦，15天内无法保证完成订单，请选择其他时间",
      //   });
      //   return;
      // }
      this.form.item = value.text;
      this.params.set("service_project", value.id);
      this.showSelectServiceItem = false;

      // if (value.id == 3) {

      // } else {
      //   this.form.time = "15天";
      //   this.params.set("service_time", 15);
      // }
      this.form.time = "30天";
      this.params.set("service_time", 30);
    },
    selectServiceTypeConfirm(value) {
      if (value.id != 1) {
        Dialog.alert({
          title: "提示",
          message: "非常抱歉！ 该功能暂未开放，敬请期待！",
        });
        return;
      }
      this.form.type = value.text;
      this.params.set("service_type", value.id);
      this.showSelectServiceType = false;
    },
    selectServiceTimeConfirm(value) {
      // if (
      //   value.id == 45 &&
      //   this.form.item != "签字和报销" &&
      //   this.form.item != ""
      // ) {
      //   Dialog.alert({
      //     title: "提示",
      //     message: "“签字”流程相对简单，无需45天处理，请选择其他时间。",
      //   });
      //   return;
      // }

      // if (value.id == 15 && this.form.item == "签字和报销") {
      //   Dialog.alert({
      //     title: "提示",
      //     message:
      //       "“签字和报销”流程相对麻烦，15天内无法保证完成订单，请选择其他时间。",
      //   });
      //   return;
      // }
      this.form.time = value.text;
      this.params.set("service_time", value.id);
      this.showSelectServiceTime = false;
    },
    selectServiceAgencyConfirm(value) {
      this.form.agency = value.text;
      this.params.set("agency", value.text);
      this.showSelectServiceAgency = false;
      this.setDefult(value);
    },
    onSubmit() {
      this.submitPost();
    },
    getOrderPrice() {
      let params = {
        service_type: null,
        service_project: null,
        service_time: null,
      };
      for (let key in params) {
        params[key] = this.params.get(key);
      }

      getOrderPrice(params).then((res) => {
        if (res.code === 200) {
          this.price = res.data.original_price.toFixed(2);
          this.reallyPrice = res.data.real_price * 100;
        }
      });
    },

    getServiceAgency() {
      getServiceAgency().then((res) => {
        if (res.code == 200) {
          this.selectServiceAgencyColumns = res.data;
        }
      });
    },
  },
};
</script>

<style lang='less'>
.apply {
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  &-form {
    height: 100%;
    margin-top: 20px;
    // padding-bottom: 70px;]
    .van-form {
      padding-bottom: 50px;
    }
    .van-cell {
      margin-bottom: 15px;
    }
    .needTips {
      .van-field__body {
        .van-field__control {
          flex-direction: column;
          align-items: flex-start;
        }
      }
      .tips {
        color: #ccc;
      }
    }
  }
  .van-submit-bar {
    // bottom: 20px;
    .van-submit-bar__bar {
      .van-submit-bar__text {
        .van-submit-bar__suffix-label {
          text-decoration: line-through;
          color: #909399;
        }
      }
    }
  }
}
</style>